package com.frxuexi.shop.view

import android.content.Context
import android.view.View
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.frxuexi.lib_base.entity.CommentBean
import com.frxuexi.lib_base.entity.ProductInfo
import com.frxuexi.lib_base.entity.ShopDetailBean
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.LiveDataBus
import com.frxuexi.shop.adapter.CommentAdapter
import com.frxuexi.shop.intent.ShopIntent
import com.frxuexi.shop.viewmodel.ShopViewModel
import com.frxuexi.shop.databinding.ActivityShopDetailBinding
import com.frxuexi.shop.intent.CartIntent
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.youth.banner.loader.ImageLoader
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

@Route(path = "/shop/ShopDetailActivity")
@AndroidEntryPoint
class ShopDetailActivity : BaseActivity<ActivityShopDetailBinding, ShopIntent, ShopViewModel>() {
    override val binding: ActivityShopDetailBinding by lazy { ActivityShopDetailBinding.inflate(layoutInflater) }
    override val vm: ShopViewModel by viewModels<ShopViewModel>()

    val commentAdapter by lazy { CommentAdapter() }
    lateinit var info:ProductInfo
    @JvmField
    @Autowired
    var id:Int=-1
    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.SELECT_ITEM->{
                                val bean = it.data as ShopDetailBean
                                info = bean.productInfo
                                binding.shopdetailTitle.setText(info.storeName)
                                binding.shopdetailPrice.setText("￥${info.price}")
                                binding.shopdetailStock.setText("库存：${info.stock}")
                                Glide.with(this@ShopDetailActivity).load(info.image).into(binding.shopdetailIv)
                            }
                            RequestType.ADD->{
                                ToastUtils.showLong("添加成功")
//                                EventBus.getDefault().post("3")
//                                LiveDataBus.with("msg",String::class.java).postValue("3")
                                finish()
                            }
                            RequestType.COMMENTS->{
                                val commentBean = it.data as CommentBean
                                commentAdapter.addData(commentBean.list)
                                commentAdapter.notifyDataSetChanged()
                            }

                            else -> {}
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)

        vm.sendIntent(ShopIntent.getShopById(id))

        val imgs= listOf<String>("http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/7a6475bba07c47bb98e5db0e0d21c8ebq5sw2kijlc.jpg",
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/37382cca048b4011bdbacd3cbbe0814daw1o5x0tco.jpg",
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/fef1aee22a04466d93693f5791d44bfd2rsm469mcr.jpg")

        binding.banner.apply {
            setImages(imgs)
                .setImageLoader(object :ImageLoader(){
                    override fun displayImage(
                        context: Context?,
                        path: Any?,
                        imageView: ImageView?
                    ) {
                        Glide.with(context!!).load(path.toString()).into(imageView!!)
                    }
                })
            setDelayTime(3000)
            start()
        }

        binding.shopdetailTab.apply {
            addTab(newTab().setText("详情"))
            addTab(newTab().setText("评论"))
            addOnTabSelectedListener(object :OnTabSelectedListener{
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    if(tab?.position==0){
                        binding.shopdetailIv.visibility=View.VISIBLE
                        binding.shopdetailCommentRv.visibility=View.GONE
                    }else{
                        binding.shopdetailIv.visibility=View.GONE
                        binding.shopdetailCommentRv.visibility=View.VISIBLE
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                }
            })
        }

        binding.shopdetailSub.setOnClickListener {
            val num = binding.shopdetailNum.text.toString().toInt()
            if(num==1){
                ToastUtils.showLong("购买数量不能小于1")
                return@setOnClickListener
            }
            binding.shopdetailNum.setText((num-1).toString())
        }

        binding.shopdetailAddnum.setOnClickListener {
            val num = binding.shopdetailNum.text.toString().toInt()
            if(num+1<=info.stock){
                binding.shopdetailNum.setText((num+1).toString())
            }else{
                ToastUtils.showLong("超出库存量")
            }
        }

        binding.shopdetailAdd.setOnClickListener {
            val map = mapOf<String, Any>(
                "cartNum" to binding.shopdetailNum.text.toString().toInt(),
                "productId" to info.id,
                "productAttrUnique" to info.id.toString()
            )
            vm.sendIntent(ShopIntent.addCart(map))
        }
        binding.shopdetailCommentRv.apply {
            adapter=commentAdapter
            layoutManager=LinearLayoutManager(this@ShopDetailActivity)
        }
        vm.sendIntent(ShopIntent.getComments(id))
    }

}